package com.webapi.core.model.persist;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

import com.webapi.core.model.common.OrderStatus;
import com.webapi.core.model.dto.OrderDto;

@Entity
@Table(name = "tb_order")
public class Order extends Base implements Serializable {

    private static final long serialVersionUID = 6587841062362606645L;

    @Column(name = "cd", nullable = false, length = 14, unique = true)
    private String cd = "F" + System.currentTimeMillis();

    @Column(name = "agent_cde", nullable = false, length = 7)
    private String agentCode;

    @Enumerated(EnumType.STRING)
    @Column(name = "status", length = 15, nullable = false)
    private OrderStatus status;

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "order")
    @Cascade(value = { CascadeType.SAVE_UPDATE })
    private List<Ticket> tickets = new ArrayList<Ticket>();

    @OneToOne(mappedBy = "order")
    @Cascade(value = { CascadeType.SAVE_UPDATE })
    private Pay pay;

    public String getCd() {
        return cd;
    }

    public OrderStatus getStatus() {
        return status;
    }

    public String getAgentCode() {
        return agentCode;
    }

    public void setAgentCode(String agentCode) {
        this.agentCode = agentCode;
    }

    public void setStatus(OrderStatus status) {
        this.status = status;
    }

    public List<Ticket> getTickets() {
        return tickets;
    }

    public void setTickets(List<Ticket> tickets) {
        this.tickets = tickets;
    }

    public Pay getPay() {
        return pay;
    }

    public void setPay(Pay pay) {
        this.pay = pay;
    }

    public static Order valueOf(OrderDto orderDto) {
        Order order = new Order();
        order.setAgentCode(orderDto.getAgentCode());
        order.setStatus(OrderStatus.Booking);
        order.setPay(Pay.valueOf(order, orderDto.getPay()));
        order.setTickets(Ticket.valueOf(order, orderDto.getTickets()));
        return order;
    }

    @Override
    public String toString() {
        return "Order [cd=" + cd + ", status=" + status + ", tickets="
                + tickets + ", pay=" + pay + ", getId()=" + getId()
                + ", getCreateTime()=" + getCreateTime() + "]";
    }

}
